package com.sijobe.installer;

import java.io.File;
import java.lang.reflect.Method;

/**
 * This class handles the backup of Minecraft.jar event. 
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @author simo_415
 */
public class ThreadBackupMCJAR extends Thread {
   
   private File mcdir;
   private Method callback;
   
   public ThreadBackupMCJAR(File mcdir) {
      this.mcdir = mcdir;
   }
   
   /**
    * Set the callback method if you want a method called when task has completed
    * 
    * @param callback - The static method to callback
    */
   public void setCallback(Method callback) {
      this.callback = callback;
   }
   
   /**
    * Signals the specified callback method when the backup is complete
    * 
    * @param err - The message to send the callback method
    */
   private void signalDone(String err) {
      if (callback != null) {
         try {
            callback.invoke(null, new Object[]{err});
         } catch (Exception e) { 
            e.printStackTrace();
         }
      }
   }
   
   public static String backupMinecraftJar(File mcdir) {
      if (mcdir == null || !mcdir.exists()) {
         return "Couldn't discover Minecraft home directory.";
      }
      File mcjar = new File(mcdir,"bin/minecraft.jar");
      if (!mcjar.exists()) {
         return "Couldn't find Minecraft.jar";
      }
      File destination = new File(mcdir,"backup/bin");
      try {
         destination.mkdirs();
      } catch (Exception e) { }
      if (!destination.exists()) {
         return "Couldn't create destination directory for backup.";
      }
      if (!Util.copyFile(mcjar,new File(destination,"Minecraft.jar." + System.currentTimeMillis()))) {
         return "Failed to make a copy of Minecraft.jar";
      }
      return null;
   }
   
   /**
    * Executes the Minecraft.jar backup.
    * 
    * @see java.lang.Thread#run()
    */
   public void run() {
      signalDone(backupMinecraftJar(mcdir));
   }
}
